<template>
  <vxe-modal
    v-model="dialogVisible"
    :close-on-click-modal="false"
    show-footer
    :title="'编辑 '+modelValue.roleName+ ' 权限'"
    resize
    show-zoom
    :fullscreen="isMobile"
  >
    <el-tree
      ref="routerTree"
      :data="treeData"
      node-key="id"
      :props="treeDefaultProps"
      highlight-current
      show-checkbox
    />
    <div slot="footer" class="dialog-footer">
      <el-button v-loading="loading" :disabled="loading" type="primary" @click="clickSubmitBtn()">提交</el-button>
    </div>
  </vxe-modal>
</template>

<script>
import Api from '@/api/upms/role'
import UpmsRouterApi from '@/api/upms/routers'
import { VxeModalMixin } from '@/mixins/vxe/VxeModalMixin'
import { pidToChildren } from '@/utils/tree'
export default {
  name: 'RoleRouterDialog',
  mixins: [VxeModalMixin],
  data() {
    return {
      treeData: [],
      treeDefaultProps: {
        children: 'children',
        label: 'metaTitle'
      },
      api: Api.saveRoleRouters,
      modelValue: {
        roleId: undefined,
        roleName: undefined,
        checkedIds: []
      }

    }
  },
  computed: {

  },
  mounted() {
    this.getAllRouters()
  },
  methods: {
    getAllRouters() {
      UpmsRouterApi.page({
        page: {
          currentPage: 1,
          pageSize: 99999
        },
        baseParams: {

        }
      }).then(({ data }) => {
        this.treeData = pidToChildren(data, { id: 'id', pid: 'pid' })
      }).then(() => {
        this.getRoleHasRouterIds()
      })
    },
    getRoleHasRouterIds() {
      Api.getRoleRouters(this.modelValue.roleId).then(({ data }) => {
        this.$nextTick(() => {
          const checkedKeys = []
          data.forEach(element => {
            const node = this.$refs['routerTree'].getNode(element)
            if (node && node.childNodes.length === 0) {
              checkedKeys.push(element)
            }
          })
          this.modelValue.checkedIds = checkedKeys
          this.$refs.routerTree.setCheckedKeys(this.modelValue.checkedIds, false)
        })
      })
    },
    clickSubmitBtn() {
      this.loading = true
      const node = this.$refs['routerTree'].getCheckedNodes(false, true)
      const checkedIds = node.map(ele => ele['id'])
      this.modelValue.checkedIds = checkedIds
      this.api(this.modelValue).then(({ code, msg }) => {
        if (code === 200200) {
          this.dialogVisible = false
          this.$emit('success', this.modelValue)
          this.loading = false
        }
        this.$message({ type: code === 200200 ? 'success' : 'error', message: msg || '保存成功' })
      }).finally(() => {
        if (this.loading) {
          setTimeout(() => {
            this.loading = false
          }, 1500)
        }
      })
    }
  }
}
</script>

<style>

</style>
